package cc.wanforme.fsync.task;

import cc.wanforme.fsync.entity.ClientNodeInfo;
import cc.wanforme.fsync.entity.SyncMeta;
import cc.wanforme.fsync.entity.po.GroupMap;
import cc.wanforme.fsync.entity.po.TickTask;
import cc.wanforme.fsync.server.ServerCenter;
import cc.wanforme.fsync.server.service.ITickTaskGroupService;
import cc.wanforme.fsync.server.service.ITickTaskService;
import cc.wanforme.fsync.util.LoggerTool;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;

import java.time.LocalDateTime;
import java.util.List;

public class JobWorker implements Job {
    private static final Logger log = LoggerTool.getLogger();
    public static final String JOB_ID = "jobId";

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap dataMap = context.getMergedJobDataMap();
        long taskId = dataMap.getLongValue(JOB_ID);
        ITickTaskGroupService taskGroupService = (ITickTaskGroupService) dataMap.get("taskGroupService");
        ITickTaskService tickTaskService = (ITickTaskService) dataMap.get("tickTaskService");
        ServerCenter serverCenter = (ServerCenter) dataMap.get("serverCenter");

        executeTask(taskId, taskGroupService, tickTaskService, serverCenter);
    }

    public void executeTask(long taskId, ITickTaskGroupService taskGroupService, ITickTaskService taskService, ServerCenter serverCenter) {
        // 获取任务
        TickTask task = taskService.getById(taskId);
        if(task == null) {
            return;
        }
        if( task.getRunning()!=null && task.getRunning()==1) {
            return;
        }
        task.setActive(1);
        task.setRunning(1);
        taskService.updateById(task);

        // 获取 task 对应的 GroupMap
        List<GroupMap> groupMaps = taskGroupService.listGroupMapByTask(taskId);
        if(groupMaps == null || groupMaps.isEmpty()) {
            return;
        }

        groupMaps.forEach(e -> {
            SyncMeta meta = new SyncMeta();
            meta.setName(e.getName());
            meta.setSource(e.getSource());
            meta.setTarget(e.getTarget());
            meta.setRewritePath(e.getRewritePath());
            meta.setCover(e.getCover()!=null && e.getCover().intValue() != 0);

            ClientNodeInfo targetNode = serverCenter.getInfoById(e.getTargetClient());
            meta.setClientNode(targetNode);
            try {
                syncData(serverCenter, meta, LocalDateTime.now());
            } catch (Exception ex) {
                String msg = "定时任务执行出现错误！ " + e.getName() + ", " + e.getSource() + " >>> " + e.getTarget();
                log.error(msg, ex);
            }
        });

        task.setRunning(0);
        task.setActive(0);
        taskService.updateById(task);
    }

    protected void syncData(ServerCenter serverCenter, SyncMeta meta, LocalDateTime  time) throws Exception {
        serverCenter.async(meta, time);
    }

}
